const mongoose = require("mongoose");

// 获取排片数据
const get = async ({
    curPage,
    eachPage
}) => {
    // 转换类型
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
    }
    // 获取model
    const schedulesModel = mongoose.model("schedules");
    // 获取当前model映射的那个集合里存在的文档总数
    data.total = await schedulesModel.countDocuments();
    // 获取总页数
    data.maxPage = Math.ceil(data.total / eachPage);
    const skipNum = (curPage - 1) * eachPage;
    data.rows = await schedulesModel.find().populate("cinemasId").populate("movieId").populate("theaterId").skip(skipNum).limit(eachPage).sort({
        _id: -1
    }).exec();

    return data;
}

// 获取电影
const getMovie = async () => {
    const moviesModel = mongoose.model("movies");
    return await moviesModel.find();
}

// 获取影院
const getCinemas = async () => {
    const cinemasModel = mongoose.model("cinemas");
    return await cinemasModel.find();
}
// 获取放映厅
const getTheaters = async ({
    _id
}) => {
    const theatersModel = mongoose.model("theaters");
    return await theatersModel.find({
        cinemasId: _id
    }).sort({
        _id: 0
    });
}

// 新增排片
const addSchedules = async ({
    movieId,
    cinemasId,
    theaterId,
    showTime,
    price
}) => {
    const schedulesModel = mongoose.model("schedules");
    // 1、新增排片信息
    const {
        _id: schedulesId
    } = await schedulesModel.create({
        movieId,
        cinemasId,
        theaterId,
        showTime,
        price
    });
    // 2、获取排片信息中，涉及的放映厅所对应的座位信息
    const seatsArr = await mongoose.model("seats").find({
        theaterId
    }).sort({
        _id: 0
    });
    // 3、创建属于当前排片信息的座位数据
    const seatingsArr = seatsArr.map(item => ({
        seatId: item._id,
        schedulesId,
        status: 0,
    }))
    // 4、把座位信息加入数据库
    await mongoose.model("seatings").create(seatingsArr);
}
// 删除排片
const removeSchedules = async ({
    _id
}) => {
    // 获取model
    const schedulesModel = mongoose.model("schedules");
    const data = await schedulesModel.remove({
        _id
    });
    // 删除排片_id拥有的选座集合
    await mongoose.model("seatings").remove({
        schedulesId: _id
    });
}

// // 获取排片的座位
const getSeatings = async schedulesId => {
    const seatingsModel = mongoose.model("seatings");
    return await seatingsModel.find({
        schedulesId
    }).populate("seatId").populate("schedulesId").sort({
        _id: 0
    }).exec();
}

// 通过排片id找到整条数据
const sortmoviesData = async _id => {
    const schedulesModel = mongoose.model("schedules");
    return await schedulesModel.find({
        _id
    }).populate("cinemasId").populate("movieId").populate("theaterId").exec();
}


// // 新增订单
const addOrder = async (seatId, userId) => {
    const seatingsModel = mongoose.model("seatings");
    const orderModel = mongoose.model("order");
    // 通过循环修改选座的状态
    for (let i = 0; i < seatId.length; i++) {
        await seatingsModel.updateOne({
            _id: seatId[i]
        }, {
            status: 1
        });
    };
    // 找到座位对应的排片ID
    const {
        schedulesId
    } = await seatingsModel.findOne({
        _id: seatId[0]
    });
    console.log(schedulesId);
    // 通过遍历的方式将整合订单信息
    let data = [{
        schedulesId,
        seatingsId: seatId,
        userId,seeState:1
    }];
    const result = await orderModel.create(data);
    if (result.length == 1) {
        return {
            status: true
        };
    } else {
        return {
            status: false
        };
    }
}

// 查询电影
const findMovie = async movieId => {
    const schedulesModel = mongoose.model("schedules");
    return await schedulesModel.find({
        movieId
    }).populate("cinemasId").populate("movieId").populate("theaterId").sort({
        _id: -1
    }).exec();
}
// 查找影院下面的电影拍片信息
const findCinemaMovie = async ({
    _cinemaId,
    _movieId
}) => {
    const schedulesModel = mongoose.model("schedules");
    return await schedulesModel.find({
        cinemasId: _cinemaId,
        movieId: _movieId
    }).populate("cinemasId").populate("movieId").populate("theaterId").sort({
        _id: -1
    }).exec();
}
// 查找影院上映了哪些电影
const findCinemaAllMovie = async ({
    _cinemaId
}) => {
    const schedulesModel = mongoose.model("schedules");
    const data = await schedulesModel.find({
        cinemasId: _cinemaId
    }).populate("cinemasId").populate("movieId").populate("theaterId").sort({
        _id: -1
    }).exec();
    // 定义一个电影去重后的影院信息
    let newScheduls = [];
    // 用来装存在的影院id
    let cinemaarr = [];
    // 遍历未去重的影院信息
    data.forEach((item => {
        // 判断影院id数组中是否已经存在
        if (!cinemaarr.includes(item.movieId._id)) {
            // 不存在将影院id存在影院Id数组中
            cinemaarr.push(item.movieId._id)
            // 将独一的信息添加到影院信息中
            newScheduls.push(item)
        }
    }))
    return newScheduls
}



module.exports = {
    get,
    getMovie,
    getCinemas,
    getTheaters,
    addSchedules,
    removeSchedules,
    getSeatings,
    addOrder,
    sortmoviesData,
    findMovie,
    findCinemaMovie,
    findCinemaAllMovie
};